// pages/FanInfo/FanInfo.js
const app = getApp();
const API = require('../../common/constant');
const util = require('../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    star: false,
    info: {},
    deleteCount: 0,
    pageIndex: 1,
    pageCount: 0,
    ifReply: false,
    commentContent: '',
    leaveWords: [],
  },
  goToPerson(e){
    console.log(e.currentTarget.dataset.id);
    let userId = wx.getStorageSync('userInfo').userId;
    if (e.currentTarget.dataset.id + '' == userId + '') {
      wx.navigateTo({
        url: '../myInformation/myInformation'
      })
    }else{
      wx.navigateTo({
        url: '../FanInfo/PersonInfo/PersonInfo?id=' + e.currentTarget.dataset.id
      })
    }
  },
  /**
   * 获取数据
   */
  getActivityInfo: function (param) {
    let sesssionID = wx.getStorageSync("sessionId");
    if (sesssionID.length == 0) {
      // console.log(sesssionID+"kkkk");
      wx.showToast({
        title: '您还没有登录，请登录',
        icon: "none",
        duration: 4000
      });
      wx.navigateTo({
        url: '../loginAndRegister/loginAndRegister'
      });
    } else {
      util.http({
        url: API.URL.EVENT.FIND_EVENTINFODETAILBYID,
        data: {
          id: param
        },
        success: (res) => {
          console.log('获取的详情为:', res.data.bussData)
          if (!res.data.bussData) {
            app.showUserInfo('活动不存在，2s后自动返回', 'none', 2000)
            setTimeout(() => {
              wx.navigateBack({})
            }, 2000)
          }
          var newdata = this.changeInfo(res.data.bussData);
          console.log(newdata);
          this.setData({
            info: newdata,
            pageIndex: 1,
            leaveWords: []
          });
          this.getLeaveWords();
        },
        fail: (rej) => {
          console.log(rej);
          wx.showToast({
            title: '获取不到活动信息',
            icon: "none",
            duration: 4000
          });
        }
      });
    }
  },
  toPersonInfo: function (e) {
    console.log(e.currentTarget.id);
    wx.navigateTo({
      url: '../myInformation/myInformation'
    })
  },
  changeInfo: function (arr) {
    if (arr.eventType == "chat") {
      arr.activityType = "#解闷聊天#";
      arr.activityColor = '#F4BC11';
    } else if (arr.eventType == "partner") {
      arr.activityType = "#美食搭伙#";
      arr.activityColor = '#FF8023';
    } else if (arr.eventType == 'find') {
      arr.activityType = "#求邂逅#";
      arr.activityColor = '#FE3232';
    }
    arr.eventStartTime = this.changeDate(arr.eventStartTime);
    arr.eventEndTime = this.changeDate(arr.eventEndTime);
    arr.registrationStartTime = this.changeDate(arr.registrationStartTime);
    arr.registrationEndTime = this.changeDate(arr.registrationEndTime);
    return arr;
  },
  changeDate: function (date) {
    let yearMonth = date.split('-');
    let dayTime = yearMonth[2].split(' ');
    let time = dayTime[1].split(':');
    let newdate = parseInt(yearMonth[1]) + "月" + parseInt(dayTime[0]) + "日 " + time[0] + ":" + time[1];
    return newdate;
  },
  tochangeFan: function (e) {
    if (this.data.info.registrationCount > 0){
      app.showUserInfo('已有人报名，不能修改活动', 'none', 2000);
      return
    }
    if (this.data.status === '已结束') {
      app.showUserInfo('活动已结束', 'none', 2000)
      return
    }
    wx.navigateTo({
      url: '../changeFanRule/changeFanRule?id=' + e.currentTarget.id + '&cityCode=' + this.data.cityCode
    })
  },
  /**
   * 跳转到报名管理页面
   */
  toEventManage: function (e) {
    wx.navigateTo({
      url: '../EventManagement/EventManagement?id=' + e.currentTarget.id + "&status=" + this.data.status
    })
  },
  getDeleteCount(e) {
    if (this.data.status === '已结束') {
      app.showUserInfo('活动已结束', 'none', 2000);
      return
    }
    if (this.data.info.registrationSuccessCount > 0) {
      app.showUserInfo('已有用户报名，不能删除活动', 'none', 2000);
      return
    }
    let EventId = e.currentTarget.id;
    let that = this;
    util.http({
      url: API.URL.EVENT.COUNT_DELETEEVENT,
      success(res) {
        console.log(res.data.bussData, EventId);
        that.deleteEvent(res.data.bussData, EventId);
      },
      fail(res) {
        app.showUserInfo('您当前的删除次数已经达到了最大限制次数', 'none', 1500);
      }
    })
  },
  /**
   * 删除 活动
   */
  deleteEvent: function (count, e) {
    let EventId = e
    let that = this;
    console.log(count);
    if (count >= 3) {
      app.showUserInfo('您当前的删除次数已经达到了最大限制次数', 'none', 1500);
    } else {
      // 数量小于3 提示删除
      wx.showModal({
        title: '提示',
        content: '删除后对方将无法赴约,确定取消嘛？' + '今日剩余删除次数：' + (3 - count),
        confirmColor: '#FE3232',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
            util.http({
              url: API.URL.EVENT.DELETE_EVENTINFO,
              data: {
                idEventInfoId: EventId
              },
              success: res => {
                console.log('删除成功');
                app.globalData.isNewIndex = true;
                app.globalData.isNewNearBy = true;
                app.globalData.isNewPublish = true;
                app.showUserInfo('成功删除该活动', 'success', 1500);
                setTimeout(() => {
                  wx.navigateBack({})
                }, 1500);
              },
              fail: rej => {
                console.log('删除失败');
                console.log(rej);
                app.showUserInfo('您当前的删除次数已经达到了最大限制次数', 'none', 1500);
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    }
  },
  toRestaurant: function () {
    let info = this.data.info;
    wx.navigateTo({
      url: `../restConfirm/restConfirm?title=${info.eventAddress}&distance=${info.distance * 1000}&address='未知'&longitude=${info.longitude}&latitude=${info.latitude}&adcode='未知'`
    });
  },

  getLeaveWords() {
    let that = this;
    util.http({
      url: API.URL.MESSAGE.FIND_EVENTMESSAGEBYPAGE,
      data: {
        id: this.data.info.id,
        pageIndex: this.data.pageIndex,
        pageSize: 4
      },
      success(res) {
        console.log('查询留言成功', res);
        that.setData({
          leaveWords: that.data.leaveWords.concat(res.data.bussData),
          pageCount: res.data.pageCount
        })
      },
      fail(res) {
        console.log('查询留言失败', res);
      }
    })
  },
  bindSarchInput(e) {
    console.log(e.detail.value)
    this.setData({
      commentContent: e.detail.value
    })
  },
  hideDelete() {
    this.setData({
      isReply: false
    })
  },
  replyReply(e) {
    let dataInfo = e.currentTarget.dataset;
    let that = this;
    console.log('replyReply', e.currentTarget.dataset.contentid, e.currentTarget.dataset.username);
    if (dataInfo.isself) {
      let showMsg = '';
      if (e.currentTarget.dataset.delete === 'y') {
        showMsg = '删除评论'
      } else {
        showMsg = '删除回复'
      }
      wx.showModal({
        title: showMsg,
        content: '是否' + showMsg,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定');
            that.deleteMessage(e.currentTarget.dataset.contentid);
          }
        }
      })
    } else {
      this.setData({
        replyer: dataInfo.username,
        contentid: dataInfo.contentid,
        isReply: true
      })
    }
  },
  giveReply() {
    if (!this.data.commentContent.trim()) {
      app.showUserInfo('请填写内容', 'none', 1000);
      return;
    }
    let that = this;
    util.http({
      url: API.URL.MESSAGE.SAVE_MESSAGEINFO,
      data: {
        idEventInfoId: this.data.info.id,
        content: this.data.commentContent,
        parentId: this.data.contentid
      },
      success(res) {
        console.log('回复成功', res)
        that.setData({
          isReply: false,
          pageIndex: 1,
          leaveWords: []
        })
        that.getLeaveWords();
      },
      fail(res) {
        console.log('回复失败', res)
      }
    })
  },
  deleteMessage(e) {
    util.http({
      url: API.URL.MESSAGE.DELETE_MESSAGEINFO,
      data: {
        replyId: e
      },
      success: (res) => {
        console.log('删除留言成功', res);
      },
      fail: (res) => {
        console.log('删除留言失败', res)
      }
    })
  },
  cleanDefault() {
    console.log('阻止冒泡')
  },
  /**
 * 生命周期函数--监听页面加载
 */
  onLoad: function (options) {
    console.log(options);
    let cityCode = options.cityCode || false;
    let isPubSuccess = options.isPubSuccess || false;
    let status = options.status || false;
    let isIndex = options.isIndex || false;
    this.getActivityInfo(options.id);
    this.setData({
      isPubSuccess: isPubSuccess,
      status: status,
      isIndex: isIndex,
      eventId: options.id,
      cityCode: cityCode
    })
    app.globalData.isNewMyFan = false;
  },
  onShow(){
    if (app.globalData.isNewMyFan){
      app.globalData.isNewMyFan = false;
      this.getActivityInfo(this.data.eventId);
    }
  },
  onReachBottom() {
    if (this.data.pageCount <= this.data.pageIndex) return
    this.setData({
      pageIndex: this.data.pageIndex + 1
    })
    this.getLeaveWords();
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.data.isPubSuccess) {
      wx.navigateTo({
        url: '../myPublishEvents/myPublishEvents?isMyPubEvent=true'
      })
    } else if (this.data.isIndex) {
      wx.switchTab({
        url: '../index/index'
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let id = this.data.info.id;
    let eventUserId = this.data.info.userId;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '还一个人玩呢？来一起约个饭吧！',
      path: '/pages/loginAndRegister/loginAndRegister?id=' + id + '&eventUserId=' + eventUserId,
      imageUrl: '../../images/shareImg.png',
      success: res => {
        // shareAppMessage: ok,
        // shareTickets 数组，每一项是一个 shareTicket ，对应一个转发对象
        // 需要在页面onLoad()事件中实现接口
        wx.showShareMenu({
          // 要求小程序返回分享目标信息
          withShareTicket: true
        });
      }
    }
  },
  
})